﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using NexTrackDesktop.Media;

namespace NexTrackDesktop.ViewModels
{
    /// <summary>
    /// This class handles displaying/linking Song to view
    /// </summary>
    public class SongViewModel : ViewModelBase{


        public SongViewModel() : this(null) { }

        /// <summary>
        /// Creates new SongViewModel for specified song.
        /// </summary>
        /// <param name="song">Song to create viewmodel for</param>
        public SongViewModel(Song song)
        {
            Song = song;
        }

        bool _selected;

        public bool Selected
        {
            get { return _selected; }
            set { _selected = value; NotifyPropertyChanged(() => Selected); }
        }

        private Song _song;
        public Song Song 
        { 
            get
            {
                return _song;
            }
            set
            {
                _song = value;
                CachedThumbSource = null;

                if (Song != null && Song.AlbumArtSource != null)
                {
                    CachedThumbSource = Client.ThumbnailCache.LocalCache(Song.AlbumArtSource);
                    if (CachedThumbSource == null)
                        Client.ThumbnailCache.DownloadComplete += ThumbnailCache_DownloadComplete;
                }

                NotifyPropertyChanged(() => Song);
            }
        }

        private Uri _cachedThumbSource;

        public Uri CachedThumbSource
        {
            get { return _cachedThumbSource; }
            set 
            { 
                _cachedThumbSource = value;
                NotifyPropertyChanged(() => CachedThumbSource);
                NotifyPropertyChanged(() => HasCachedThumbnail); 
            }
        }

        public bool HasCachedThumbnail { get { return _cachedThumbSource != null; } }


        void ThumbnailCache_DownloadComplete(Uri remoteUri)
        {
            if (Song.AlbumArtSource == remoteUri)
            {
                Client.ThumbnailCache.DownloadComplete -= ThumbnailCache_DownloadComplete;
                CachedThumbSource = Client.ThumbnailCache.LocalCache(Song.AlbumArtSource);
            }
        }
    }
}
